<template>
  <div>
    <el-dialog :title="$t('message.strMarkupTitle')" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="positon-x:">
          <el-input v-model="form.input1X" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="positon-y:">
          <el-input v-model="form.input1Y" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('message.strCancel')}}</el-button>
        <el-button type="primary" @click="onAddMarkupCommitClick">{{$t('message.strConfirm')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="输入文字" :visible.sync="showTextInputDialog">
      <el-form :model="form">
        <el-form-item label>
          <el-input v-model="textInputDialogContent" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" @before-close="onTextInputDialogOkClick(false)">
        <el-button @click="onTextInputDialogOkClick(false)">取消</el-button>
        <el-button type="primary" @click="onTextInputDialogOkClick(true)">确定</el-button>
      </div>
    </el-dialog>

    <el-row>
      <el-col :span="18" align="left">
        <el-upload
          class="upload-demo"
          ref="upload"
          :action="uploadFileUrl"
          mulitiply
          ow-file-list="false"
          :file-list="fileSelectedList"
          :auto-upload="false"
          :on-change="onFileSelectChange"
          :on-exceed="handleExceed"
          :on-success="onFileUploadSuccess"
          :show-file-list="false"
          accept=".dwg, .dxf, .wmf, .jpg, .png, .tiff, .tif, .gif, .bmp"
        >
          <el-button
            class="inputfile"
            slot="trigger"
            size="small"
          >{{$t('message.selectedFileName')}}</el-button>
          <!-- <el-button class="upload-btn" size="small" @click="submitUpload">{{strUpload}}</el-button> -->
          <el-button
            class="upload-btn"
            size="small"
            @click="queryHelloStr"
          >{{$t('message.strUpload')}}</el-button>
        </el-upload>
      </el-col>

      <el-col :span="3">
        <div align="right">
          <el-button size="small" @click="changeLanguage">{{$t('message.strChangeLang')}}</el-button>

          <el-button size="small" @click="testMarkup">test markup</el-button>
        </div>
      </el-col>

      <el-col :span="3">
        <div align="right">
          <el-button size="small" @click="dialogFormVisible = true">{{$t('message.strAddMarkup')}}</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row style="border: 2px solid #333333;">
      <el-col>
        <div v-if="showType == 0">
          <addShapesLayout
            ref="shapeslayout"
            class="shapes-layout"
            @handleSelectChange="onShapeSelectChange"
          />
          <selectShapeParams
            ref="paramslayout"
            class="params-layout"
            @handleSelectChange="onParamsSelectChange"
            :selectedShapeParam="selectedParams"
          />

          <div class="markup-select-layout">
            <Button @click="getMarkupFile">点击上传</Button>
            <!-- <input ref="filElem" type="file" class="upload-file" @change="getMarkupFile" /> -->

            <!-- <input
              type="file"
              ref="upload"
              accept=".xml"
              @change="executorListchange"
              id="file_executor"
              class="outputlist_upload"
            />-->
          </div>

          <div id="viewer" style="height: 800px;"></div>
        </div>

        <viewer
          v-if="showType == 1"
          id="viewer"
          :options="options"
          :images="imgSelectedUrl"
          class="images"
        >
          <template>
            <img :src="imgSelectedUrl" style="display: none;" />
          </template>
        </viewer>
      </el-col>
    </el-row>

    <el-row v-if="showType == 0">
      <el-col :span="9">
        <div class="radios">
          <el-radio-group v-model="radioModel" @change="onRadioChange">
            <el-radio :label="1">{{$t('message.strModeZoom')}}</el-radio>
            <el-radio :label="2">{{$t('message.strModePan')}}</el-radio>
          </el-radio-group>
          <div class="radio-tip">{{$t('message.strModeTip')}}</div>
        </div>
      </el-col>

      <el-col :span="15">
        <div class="positions" align="right">
          <el-button @click="resetSvgView">{{$t('message.strPosReturn')}}</el-button>
          <el-tag style="width: 200px;text-align: left;">X:{{mousePosX}}</el-tag>
          <el-tag style="width: 200px;text-align: left;">Y:{{mousePosY}}</el-tag>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script src="../../js/index.js"></script>
<!-- <script src="../js/d3.v5.js"></script> -->
<script src="../..//js/vue-resource.min.js"></script>
<script src="../../js/jquery.min.js"></script>
<script src="../../js/tiff.js"></script>

<script src="node_modules/viewerjs/dist/viewer.js"></script>
<script src="node_modules/v-viewer/dist/v-viewer.js"></script>

<script>
// import * as d3 from "d3";
/* eslint-disable */
import * as d3 from "../../js/d3.v5.js";
import * as svg_opt from "../../js/svg_opt.js";
import * as const_data from "../../js/const.js";

import store from "./_store";

import { mapState } from "vuex";
import i18n from "@/i18n/i18n.js";
import addShapesLayout from "./_components/addShapesLayout";
import selectShapeParams from "./_components/selectShapeParams";

// import DeviceAdd from './_components/DeviceAdd';

/* eslint-enable */
var serverURL = "http://192.168.0.100:8071/spring/";

export default {
  components: {
    addShapesLayout,
    selectShapeParams,
  },

  data: function () {
    return {
      xmlfile: "",
      uploadFileUrl: serverURL + "tosvg/upload",
      checkFileUrl: serverURL + "tosvg/getOutFilePath",

      selectedFile: null,

      languageSelect: "cn",
      checkFileName: "",
      loading2: false,
      radioModel: 1, // scale position
      mousePosX: 0,
      mousePosY: 0,
      fileSelectedList: [],
      // imgSelectedList: [],
      imgSelectedUrl: "",
      shouldRunTimer: false,
      timer: "",

      dialogFormVisible: false,
      form: {
        input1X: "",
        input1Y: "",
        input2X: "",
        input2Y: "",
      },

      options: {
        inline: true,
        button: false,
        navbar: false,
        title: false,
        toolbar: false,
        tooltip: false,
        fullscreen: false,
      },

      showTiff: true,
      showType: 0, // 0 svg  1 pic
      svg: null,
      zoom: null,
      svgSourceUrl: require("../../assets/model/136-001A.svg"),
      transScale: {
        transX: 0,
        transY: 0,
        scale: 0,
        transYRatio: -100,
      },

      selectedShapeId: 0,
      selectedParams: {},
      showTextInputDialog: false,
      textInputDialogContent: "textInputDialogContent",
    };
  },

  watch: {
    languageSelect(val) {
      this.selectedFileName =
        this.fileSelectedList[0] != null
          ? this.fileSelectedList[0].name
          : this.strSelectedFileName;
    },
    selectedParams(val) {
      svg_opt.setGParams(val);
    },
  },

  created() {
    if (
      !(this.$storeKeys.HELLO_STORE_KEY in this.$store._modules.root._children)
    ) {
      this.$store.registerModule(
        this.$storeKeys.HELLO_STORE_KEY,
        store.create()
      );
    }
  },

  computed: {
    ...mapState(["lang"]),

    getHelloState() {
      return this.$store.getters[`${this.$storeKeys.HELLO_STORE_KEY}/getState`];
    },
  },

  mounted() {
    console.log("app_mounted");
    // this.AddSvg(this.svgSourceUrl, "viewer");
    // this.selectedParams = this.$refs.paramslayout.getParamsSelect();
    this.getParamsSelect("e");
    svg_opt.AddSvg(this.svgSourceUrl, "viewer", this.onSvgMousePosChange);
    svg_opt.SetSvgMouseMode(1);
    svg_opt.setSelectCallBack(this.updateParamOnSelected);
    svg_opt.setOpenInputTextCallBack(this.toShowTextInputDialog);
  },

  methods: {
    getMarkupFile(filePath) {
      filePath = "/test.xml";

      // 创建一个新的xhr对象
      let xhr = null;
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
      } else {
        // IE
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      }
      xhr.open("GET", filePath, false);
      xhr.overrideMimeType("text/html;charset=utf-8");
      xhr.send(null);
      console.log(xhr.responseText.replace(/\s*/g, ""));
      var xmlStr = xhr.responseText;
      var parser = new DOMParser();
      var xmlDoc = parser.parseFromString(xmlStr, "text/xml");

      //提取数据
      var countrys = xmlDoc.getElementsByTagName("Entity");

      for (var i = 0; i < countrys.length; i++) {
        var markupData = this.genMarkupDataFromFile(countrys[i]);

        var testRect = null;
        if (markupData.fEntType == 1)
          testRect = new svg_opt.MarkupLine(markupData, markupData.fEntType);
        if (markupData.fEntType == 2)
          testRect = new svg_opt.MarkupLine(markupData, markupData.fEntType);
        if (markupData.fEntType == 3)
          testRect = new svg_opt.MarkupLine(markupData, markupData.fEntType);
        if (markupData.fEntType == 4)
          testRect = new svg_opt.MarkupRect(markupData, markupData.fEntType);
        if (markupData.fEntType == 5)
          testRect = new svg_opt.MarkupRect(markupData, markupData.fEntType);
        if (markupData.fEntType == 6)
          testRect = new svg_opt.MarkupEllipse(markupData, markupData.fEntType);
        if (markupData.fEntType == 7)
          testRect = new svg_opt.MarkupArc(markupData, markupData.fEntType);
        if (markupData.fEntType == 8)
          testRect = new svg_opt.MarkupHandDraw(
            markupData,
            markupData.fEntType
          );
        if (markupData.fEntType == 9)
          testRect = new svg_opt.MarkupHandDraw(
            markupData,
            markupData.fEntType
          );
        if (markupData.fEntType == 10)
          testRect = new svg_opt.MarkupText(markupData, markupData.fEntType);
      }
    },

    genMarkupDataFromFile(e) {
      var markupData = {};
      var pointList = [];
      var points = e.getElementsByTagName("Point");

      for (var i = 0; i < points.length; i++) {
        var tempPoint = points[i];
        pointList.push({
          x: tempPoint.getAttribute("x"),
          y: tempPoint.getAttribute("y"),
          z: tempPoint.getAttribute("z"),
        });
      }
      markupData.pointList = pointList;

      var getValueAndFliterDot = function (parentTag, tagName) {
        var type = parentTag.getElementsByTagName(tagName)[0].textContent;
        var typeNew = type.replace(/"/g, "");
        return typeNew;
      };

      var nRGBLColor_temp = getValueAndFliterDot(e, "nRGBLColor");
      var nRGBLColor_temp_temp =
        "#" + nRGBLColor_temp.replace("0x00", "").split("").reverse().join("");
      markupData.nRGBLColor = nRGBLColor_temp_temp;

      var nRGBFillColor_temp = getValueAndFliterDot(e, "nRGBFillColor");
      var nRGBFillColor_temp_temp =
        "#" +
        nRGBFillColor_temp.replace("0x00", "").split("").reverse().join("");
      markupData.nRGBFillColor = nRGBFillColor_temp_temp;

      var nRGBTextColor_temp = getValueAndFliterDot(e, "nRGBTextColor");
      var nRGBTextColor_temp_temp =
        "#" +
        nRGBTextColor_temp.replace("0x00", "").split("").reverse().join("");
      markupData.nRGBTextColor = nRGBTextColor_temp_temp;

      // markupData.nRGBLColor = getValueAndFliterDot(e, "nRGBLColor");
      // markupData.nRGBFillColor = getValueAndFliterDot(e, "nRGBFillColor");
      // markupData.nRGBTextColor = getValueAndFliterDot(e, "nRGBTextColor");
      markupData.sFillType = getValueAndFliterDot(e, "sFillType");
      markupData.wLineThick = getValueAndFliterDot(e, "wLineThick");
      markupData.sLineStyle = getValueAndFliterDot(e, "sLineStyle");

      markupData.sFontHeight = getValueAndFliterDot(e, "sFontHeight");
      markupData.strTextContents = getValueAndFliterDot(e, "strTextContents");
      markupData.fEntType = getValueAndFliterDot(e, "fEntType");
      return markupData;
    },

    testMarkup() {
      var markupData = {};
      var pointList = [];

      // pointList.push({x:94.312318, y:364.833324, z:0.000000 });
      // pointList.push({x:439.542003, y:283.635857, z:0.000000 });
      // // <Point x="94.312318" y="364.833324" z="0.000000"></Point>
      // // <Point x="439.542003" y="283.635857" z="0.000000"></Point>
      markupData.pointList = const_data.testPointList;

      var lineColor = "#0000FF";
      var fillColor = "#80FF80";
      var textColor = "#808080";

      markupData.nRGBLColor = lineColor;
      markupData.nRGBFillColor = fillColor;
      markupData.nRGBTextColor = textColor;
      markupData.sFillType = 1;
      markupData.wLineThick = 10;
      markupData.sLineStyle = 4;
      markupData.sFontHeight = 113;
      markupData.text = "测试一下文字信息";

      var testRect = new svg_opt.MarkupRect(markupData, "8");

      var markupData2 = {};
      var pointList2 = [];

      // <Point x="33.082678" y="303.950747" z="0.000000"></Point>
      // <Point x="54.561550" y="285.461451" z="0.000000"></Point>

      pointList2.push({ x: 33.082678, y: 285.461451, z: 0.0 });
      pointList2.push({ x: 54.56155, y: 303.950747, z: 0.0 });
      pointList2.push({ x: 500, y: 200, z: 0.0 });

      markupData2.pointList = pointList2;

      var lineColor = "#0000FF";
      var fillColor = "#80FF80";
      var textColor = "#808080";

      markupData2.nRGBLColor = lineColor;
      markupData2.nRGBFillColor = fillColor;
      markupData2.nRGBTextColor = textColor;
      markupData2.sFillType = 1;
      markupData2.wLineThick = 10;
      markupData2.sLineStyle = 4;
      markupData2.sFontHeight = 113;
      markupData2.text = "一二三四五";

      // var testRect = new svg_opt.MarkupText(markupData2, "3");
    },

    onFileSelectChange: function (file, fileList) {
      console.log("onFileSelectChange");
      this.fileSelectedList = [];

      this.fileSelectedList[0] = file;
      console.log(this.fileSelectedList);
      this.selectedFileName =
        this.fileSelectedList[0] != null
          ? this.fileSelectedList[0].name
          : this.strSelectedFileName;
    },

    onImgSelectChange: function (file, fileList) {
      console.log("onImgSelectChange");
      var self = this;
      if (
        file.name.lastIndexOf(".tiff") != -1 ||
        file.name.lastIndexOf(".tif") != -1
      ) {
        // var orignCanvas = document.getElementById("tiff-image");
        // var canvasParent = orignCanvas.parentNode;

        var xhr = new XMLHttpRequest();
        xhr.responseType = "arraybuffer";
        xhr.open("GET", file.url);
        xhr.onload = function (e) {
          var tiff = new Tiff({ buffer: xhr.response });
          var canvas = tiff.toCanvas();
          // canvas.height = 1000;
          // canvas.width = 1000;

          // canvasParent.replaceChild(canvas, orignCanvas);

          if (canvas) {
            self._data.showTiff = true;
          }
        };
        xhr.send();
        self._data.imgSelectedUrl = "";
      } else {
        self._data.imgSelectedUrl = file.url;
        self._data.showTiff = true;
      }
    },

    handleExceed(files, fileList) {
      console.log("handleExceed");
      fileList[0].name = files[0].name;
      this.selectedFileName =
        this.fileSelectedList[0] != null
          ? this.fileSelectedList[0].name
          : this.strSelectedFileName;
    },

    onFileUploadSuccess(response, file, fileList) {
      console.log("onFileUploadSuccess");
      console.log(response);
      var reName = response.fileName;
      var obj = reName.lastIndexOf(".");

      var fileType = this.fnGetExtension(this.selectedFileName);
      var checkType =
        fileType == ".tif" || fileType == ".tiff" ? ".png" : ".svg";

      this.checkFileName = reName.substr(0, obj) + checkType;
      this.shouldRunTimer = true;
      this.checkIsFileInServer();
    },

    submitUpload() {
      var index = this.selectedFileName.lastIndexOf(".dwg");

      var fileType = this.fnGetExtension(this.selectedFileName);
      var showTypeSvgFile = ".dwg/.dxf/.wmf/.tif/.tiff";
      if (showTypeSvgFile.lastIndexOf(fileType) != -1) {
        this.$refs.upload.submit();
        this.loading2 = true;
        // AddSvg('model/2ap0001-1.svg', 'viewer');

        if (this.selectedFileName.indexOf("2ap0001-1") != -1)
          this.transScale.transYRatio = -5;
        else this.transScale.transYRatio = -100;

        this.showType = 0;
      } else {
        this.imgSelectedUrl = this.fileSelectedList[0].url;
        this.showType = 1;
      }
    },

    changeLanguage() {
      let lang = "";
      this.lang === "ja" ? (lang = "cn") : (lang = "ja");
      this.$store.commit("switchLang", lang);
    },

    onRadioChange(value) {
      d3.SetMouseMode(value);
    },

    onAddMarkupCommitClick(value) {
      this.dialogFormVisible = false;
      var x = parseFloat(this.form.input1X);
      var y = parseFloat(this.form.input1Y);
      this.addSimpleMarkup(x, y);
    },

    resetSvgView() {},

    onSvgMousePosChange(posX, posY) {
      this.mousePosX = posX;
      this.mousePosY = posY;
    },

    onAddMarkupCommitClick(value) {
      this.dialogFormVisible = false;
      var x = parseFloat(this.form.input1X);
      var y = parseFloat(this.form.input1Y);
      svg_opt.AddSimpleMarkup(x, y);
    },

    onTestClick(e) {
      this.queryHelloStr();
    },

    queryHelloStr() {
      this.$store.dispatch(
        `${this.$storeKeys.HELLO_STORE_KEY}/queryHelloAction`,
        {}
      );
    },

    onShapeSelectChange(e) {
      console.log(e);
      this.selectedShapeId = e.selectedShapeId; // 图形id
      if (e.selectedShapeId == 0) {
        svg_opt.changeGlobalState(0, -1);
      } else {
        svg_opt.changeGlobalState(3, this.selectedShapeId); // add状态
      }
    },

    onParamsSelectChange(e) {
      console.log(e);
      this.selectedParams = e;
    },

    getParamsSelect(e) {
      var _selectedParams = this.$refs.paramslayout.getParamsSelect();
      this.selectedParams = _selectedParams;
    },

    updateParamOnSelected(e) {
      this.selectedParams = e;
    },

    onTextInputDialogOkClick(e) {
      this.showTextInputDialog = false;
      var _selectedParams = this.$refs.paramslayout.getParamsSelect();
      if (e) _selectedParams.text = this.textInputDialogContent;
      this.selectedParams = _selectedParams;
      svg_opt.setGParams(val);

      svg_opt.onInputDialogClose();
    },

    toShowTextInputDialog(e) {
      this.showTextInputDialog = true;
      this.textInputDialogContent = e;
    },
  },
};
</script>

<style>
html {
  height: 100%;
}

body {
  width: 100%;
  height: 100%;
  background-color: #f2f2f2;
  color: #f2f2f2;
  font-family: "inconsolata";
  font-size: 15px;
  line-height: 18px;
  overflow-x: hidden;
}

#app {
  margin: 20px;
}

::webkit-scrollbar {
  display: none;
}

/* */
.el-input__inner {
  border: 2px solid #86bce6;
}

/* */
#viewer {
  height: 800px;
}

.inputfile {
  width: 390px;
}

.upload-btn {
  margin-left: 10px;
}

.radios {
  border: 1px solid #c4c7cc;
  padding: 10px;
  margin-top: 17px;
}

.radio-tip {
  position: absolute;
  left: 10px;
  top: 5px;
  background-color: #f2f2f2;
  color: #333333;
  font-size: 14px;
  padding-left: 10px;
  padding-right: 10px;
}

.el-radio__input.is-checked + .el-radio__label {
  color: #333333;
}

.el-radio__input.is-checked .el-radio__inner {
  border-color: #333333;
  background: #333333;
}

.positions {
  margin-top: 10px;
  margin-right: -5px;
}

.el-tag {
  background-color: rgba(255, 255, 255, 0);
  padding: 0 10px;
  height: 32px;
  line-height: 30px;
  font-size: 12px;
  color: #333333;
  border-radius: 4px;
  box-sizing: border-box;
  border: 1px solid #333333;
  white-space: nowrap;
}

.demo-image__preview {
  width: 500px;
  height: 500px;
}

.shapes-layout {
  position: absolute;
  left: 0;
  top: 50px;
  width: 40px;
}

.markup-select-layout {
  position: absolute;
  right: 0;
  bottom: 0;
}

.params-layout {
  position: absolute;
  left: 0;
  height: 20px;
}
</style>